package cn.lyq.card.ui.order

import android.content.Context
import android.content.Intent
import androidx.lifecycle.Observer
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.model.OrderConfirmInfo
import cn.lyq.card.data.src.Status
import cn.lyq.card.ui.web.WebPayActivity
import cn.lyq.card.utils.setClick
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.act_order_confrim.*


class OrderPayFailedActivity : BaseActivity() {

    private val mModel by lazy {
        getVM(OrderVM::class.java)
    }
    private val mInfo by lazy {
        intent.getSerializableExtra(KEY_INFO)
            ?.takeIf { it is OrderConfirmInfo }
            ?.run { this as OrderConfirmInfo }
    }

    companion object {
        private const val KEY_INFO = "INFO"

        @JvmStatic
        fun start(context: Context, info: OrderConfirmInfo?) {
            val starter = Intent(context, OrderPayFailedActivity::class.java)
                .putExtra(KEY_INFO, info)
            context.startActivity(starter)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.act_order_pay_failed
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_pay_failed)
        tvAliPay.isSelected = true
    }

    override fun initListener() {
        super.initListener()
        tvAliPay.setClick {
            tvAliPay.isSelected = true
            tvWeChatPay.isSelected = false
        }
        tvWeChatPay.setClick {
            tvAliPay.isSelected = false
            tvWeChatPay.isSelected = true
        }
        tvConfirm.setClick {
            updatePaymentType()
        }
    }

    private fun updatePaymentType() {
        mModel.updatePaymentType(mInfo?.orderId ?: "", if (tvAliPay.isSelected) 1 else 2)
            .observe(this, Observer {
                when (it?.status) {
                    Status.LOADING -> showLoading()
                    Status.SUCCESS -> {
                        mInfo?.payUrl = it.requireData().payUrl
                        WebPayActivity.start(this, mInfo)
                        dismissLoading()
                        finish()
                    }
                    Status.ERROR -> {
                        ToastUtils.showShort(it.message.getMsg())
                        dismissLoading()
                    }
                }
            })
    }

    override fun onBackPressed() {
        OrderCancelFg().show(supportFragmentManager, "OrderCancelFg")
    }
}